package com.itwxz.forum.controller.mobile;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itwxz.common.core.domain.R;
import com.itwxz.forum.domain.po.ForumPost;
import com.itwxz.forum.domain.vo.ForumPostListVo;
import com.itwxz.forum.service.ForumPostService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@Tag(name = "帖子接口", description = "论坛帖子相关操作")
@RequestMapping("/forum/mobile/post")
@RequiredArgsConstructor
public class ForumPostMobileController {
    private final ForumPostService postService;


    @Operation(
            summary = "创建帖子",
            description = "提交一个新的论坛帖子，支持图文内容"
    )
    @PostMapping
    public R<String> createPost(@Validated @RequestBody ForumPost post) {
        return R.ok(postService.createPost(post));
    }

    @SaIgnore
    @Operation(
            summary = "获取帖子列表",
            description = "分页查询帖子列表，可按关键词搜索"
    )
    @GetMapping("/list")
    public R<IPage<ForumPostListVo>> listPost(int pageNum, int pageSize, String query) {
        return R.ok(postService.getPostPageList(pageNum, pageSize, query));
    }

    /**
     * 查询我的帖子列表（分页）
     */
    @Operation(
            summary = "查询我的帖子",
            description = "分页查询当前用户发布的帖子"
    )
    @GetMapping("/my")
    public R<IPage<ForumPostListVo>> myPosts(int pageNum, int pageSize) {
        return R.ok(postService.getPostPageMy(pageNum, pageSize));
    }


    /**
     * 查询我的收藏列表（分页）
     */
    @Operation(
            summary = "查询我的收藏",
            description = "分页查询当前用户收藏的帖子"
    )
    @GetMapping("/my-collect")
    public R<IPage<ForumPostListVo>> myCollect(int pageNum, int pageSize) {
        return R.ok(postService.getPostPageMyCollect(pageNum, pageSize));
    }

    //TODO 未能删除同步化
    @DeleteMapping("/{postId}")
    @Operation(summary = "删除帖子", description = "删除指定 ID 的帖子，仅限作者本人操作")
    public R<String> deletePost(@PathVariable String postId) {
        ForumPost post = postService.getById(postId);
        if (post == null) return R.fail("帖子不存在");

        String userId = String.valueOf(post.getUserId());
        if (!StpUtil.getLoginIdAsString().equals(userId))
            return R.fail("无权删除该帖子");

        postService.removeById(postId);
        return R.ok("删除成功");
    }
}
